# -*- coding: utf-8 -*-
import json
import random
import requests
from odoo import api, http, models,fields,_,SUPERUSER_ID
from odoo.exceptions import AccessDenied, AccessError, UserError, ValidationError

server_url = "https://ecmec.com.cn"
db_name = "odoo16-test"
username = "admin"
password = "DIbohao1"
json_endpoint = "%s/jsonrpc" % server_url
headers = {"Content-Type": "application/json"}

class MeasCtlRpc(models.Model):
    _name="meas.ctl.rpc"
    _description="jsonrpc methodpackage"
    def get_json_payload(self,service, method, *args):
        return json.dumps(
            {
                "jsonrpc": "2.0",
                "method": "call",
                "params": {"service": service, "method": method, "args": args},
                "id": random.randint(0, 100000000),
            }
        )
    def get_user(self,db_name,username,password):
        payload = self.get_json_payload("common", "login", db_name, username, password)
        response = requests.post(json_endpoint, data=payload, headers=headers)
        # response = requests.post(json_endpoint, data=payload, headers={'Connection':'close'})
        response.close()
        user_id = response.json()["result"]
        if user_id:
            print("Success: User id is", user_id)
            return user_id
        else:
            print("Failed: wrong credentials")
            return None

    def fetch_data(self,domain,model_name,fields):
        user_id=self.get_user(db_name,username,password)
        if user_id:
            # payload = get_json_payload("object", "execute_kw",db_name, user_id, password, model_name, 'search',[domain] )
            # res = requests.post(json_endpoint, data=payload, headers=headers).json()
            # print('Search Result:', res)
            # payload = get_json_payload("object", "execute_kw", db_name, user_id, password,model_name,'read', [res['result'],[]])
            # res = requests.post(json_endpoint, data=payload, headers=headers).json()
            # print('Books data:', res)

            payload = self.get_json_payload("object", "execute_kw", db_name, user_id, password, model_name,'search_read', [domain, 
            fields])
            res = requests.post(json_endpoint, data=payload, headers=headers).json()
            # print('Books data:', res)
            return res['result']
        else:
            raise ValidationError("Failed: wrong credentials")
            # print("Failed: wrong credentials")

    def operation_create(self,model_name,create_data): 
        user_id=self.get_user(db_name,username,password)
        if user_id:
        # creates the books records 
            # create_data = [
            #     {'name': 'Book 1', 'date_release':
            #     '2019-01-26'},
            #     {'name': 'Book 3', 'date_release':
            #     '2019-02-12'},
            #     {'name': 'Book 5', 'date_release':
            #     '2019-05-08'},
            #     {'name': 'Book 7', 'date_release':
            #     '2019-05-14'} ]
            payload = self.get_json_payload("object", "execute_kw",db_name, user_id, password, model_name,'create',[create_data])
            res = requests.post(json_endpoint, data=payload,headers=headers).json() 
            print("created:", res) 
            return res.get('error',False)
        else:
            raise ValidationError("Failed: wrong credentials")
            # print("Failed: wrong credentials")

    def operation_write(self,user_id,model_name,rec_to_write,write_data,): #operate=['create','write','unlink']
        user_id=self.get_user(db_name,username,password)
        if user_id:
            # rec_to_write = books_ids[1]
            # write_data = {'name': 'Book 2'}
            payload = self.get_json_payload("object", "execute_kw",db_name, user_id, password, model_name,'write', [rec_to_write, write_data])
            res = requests.post(json_endpoint, data=payload,headers=headers).json() 
            print("Books written:", res)
        else:
            raise ValidationError("Failed: wrong credentials")
            # print("Failed: wrong credentials")
    def operation_unlink(self,user_id,model_name,rec_to_unlink):
        user_id=self.get_user(db_name,username,password)
        if user_id:
            # book_to_unlink = books_ids[2:]
            payload = self.get_json_payload("object", "execute_kw", db_name, user_id, password, model_name, 'unlink', [rec_to_unlink])
            res = requests.post(json_endpoint, data=payload,headers=headers).json() 
            print("Books deleted:", res)
        else:
            raise ValidationError("Failed: wrong credentials")
            # print("Failed: wrong credentials")

    def run_method(self,user_id,model_name,method,param_list):
        user_id=self.get_user(db_name,username,password)
        if user_id:
            # payload = self.get_json_payload("object", "execute_kw",db_name, user_id, password,model_name, 'create', [{'name': 'Book 1','state': 'draft'}])
            # res = requests.post(json_endpoint, data=payload,headers=headers).json()
            # print("Has create access:", res['result']) 
            # book_id = res['result']
            # Change the book state by calling make_available
            # method
            payload = self.get_json_payload("object", "execute_kw",db_name, user_id, password,model_name, method, param_list) 
            res = requests.post(json_endpoint, data=payload,headers=headers).json()
            # Check the book status after method call
            # payload = self.get_json_payload("object", "execute_kw",db_name, user_id, password,model_name, 'read', [book_id,['name', 'state']])
            # res = requests.post(json_endpoint, data=payload,headers=headers).json()
            # print("Book state after the method call:",res['result'])
        else:
            raise ValidationError("Failed: wrong credentials")
            # print("Failed: wrong credentials")

    def find_dict_by_value(self,dicts, key, value):
        # dicts = [
        #     {'id': '001', 'name': 'Alice'},
        #     {'id': '002', 'name': 'Bob'},
        #     {'id': '003', 'name': 'Charlie'},
        # ]
        res=[]
        for d in dicts:
            if key in d and d[key][0] == value:
                res.append(d)
        return res

        result = find_dict_by_value(dicts, 'id', '001')
        print(result)  # 输出：{'id': '001', 'name': 'Alice'}





